<template>
  <!--表单组件-->
  <div>

    <el-row :gutter="10">
      <el-col :span="6">
        <el-card style="height:60vh;max-height: 60vh;overflow-y: scroll">
          <el-input v-model="searchType" placeholder="输入关键字搜索"></el-input>
          <el-tree
              ref="typeTree"
              :data="typeList"
              :props="defaultProps"
              show-checkbox
              @check-change="handleCheckChange">
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card style="height:60vh;max-height: 60vh;overflow-y: scroll">
          <el-input v-model="searchGoods" placeholder="输入关键字搜索"></el-input>
          <el-table ref="leftTable" stripe border @selection-change="changeLeftSelect"
                    :data="goodsList" size="small" style="width: 100%;">
            <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
            <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
            <el-table-column :render-header="crud.renderHeader" prop="goodsCode" label="编码"/>
            <el-table-column :render-header="crud.renderHeader" prop="goodsName" label="名称"/>
          </el-table>

        </el-card>
      </el-col>
      <el-col :span="2">
        <div style="height:60vh;max-height: 60vh;display: flex;flex-direction: column;justify-content: center">
          <el-button @click="addRight" type="primary" plain>添加-></el-button>
          <br/>
          <el-button style="margin-top: 20px" @click="addLeft" type="danger" plain><-删除</el-button>
        </div>

      </el-col>
      <el-col :span="8">
        <el-card style="height:60vh;max-height: 60vh;overflow-y: scroll">
          <el-table ref="rightTable" stripe border @selection-change="changeResultGoodsSelect"
                    :data="resultGoods" size="small" style="width: 100%;">
            <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
            <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
            <el-table-column :render-header="crud.renderHeader" prop="goodsCode" label="编码"/>
            <el-table-column :render-header="crud.renderHeader" prop="goodsName" label="名称"/>

            <el-table-column :render-header="crud.renderHeader" prop="goodsBrandName" label="商品品牌"/>
            <el-table-column :render-header="crud.renderHeader" prop="goodsTagName" label="商
            品分类"/>
<!--            <el-table-column :render-header="crud.renderHeader" prop="firstUnitName" label="可用量"/>-->
<!--            <el-table-column :render-header="crud.renderHeader" prop="firstUnitCount" label="可用辅数量"/>-->
            <el-table-column :render-header="crud.renderHeader" prop="secondUnitName" label="辅数量" width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.boxNum"
                          @input="computeGoodsCount(scope.row,1)" placeholder="">
                  <template slot="append"> {{ scope.row.boxUnitName }}</template>
                </el-input>
                <el-input v-model="scope.row.mainNum"   @input="computeGoodsCount(scope.row,2)"
                          placeholder="">
                  <template slot="append"> {{ scope.row.mainUnitName }}</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column :render-header="crud.renderHeader" prop="goodsCount" label="数量">
              <template slot-scope="scope">
                <el-input v-model="scope.row.goodsCount" @input="couputedGoodsUnitCount(scope.row)"
                          placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>
            <!--            <el-table-column :render-header="crud.renderHeader" prop="goodsMoney" label="单价"/>-->
            <el-table-column :render-header="crud.renderHeader" prop="noTaxAmount" label="未税金额"/>
            <el-table-column :render-header="crud.renderHeader" prop="taxAmount" label="含税金额"/>
            <!--            <el-table-column :render-header="crud.renderHeader" prop="fCustomerName" label="折扣率"/>-->
            <!--            <el-table-column :render-header="crud.renderHeader" prop="taxRate" label="详细可用量"/>-->
            <!--            <el-table-column :render-header="crud.renderHeader" prop="helpSign" label="助记符"/>-->
          </el-table>
        </el-card>
      </el-col>

    </el-row>

    <div class="cu-footer">
      <el-button type="text" @click="closedDialog()">取消</el-button>
      <el-button type="primary" @click="submitCU">确认</el-button>
    </div>
  </div>
</template>

<script>
import {getTypeList} from "@/api/erp/basGoodsType";
import {getGoods} from "@/api/erp/basGoods";

export default {
  name: "addBatch",
  props: {
    showAddBatchDialog: {
      type: Boolean,
      default: true
    },
    params: {
      //销售单类型
      type: Object,
      default: function () {
        return {}
      }
    },
    list:Array,//已经选择的数据

  },
  data() {
    return {
      typeList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      searchType: "",
      searchGoods: "",
      goodsList: [],
      selectTypes: [],//选中的分类
      resultGoods: [],//右边的数据民
      leftGoodsSelect: [],
      resultGoodsSelect: []
    }
  },
  created() {
    this.getTypeList()
    this.resultGoods = JSON.parse(JSON.stringify(this.list))
  },
  watch: {
    searchGoods: function (n) {
      this.getGoodsList()
    }
  },
  methods: {
    //动态计算商品数量
    computeGoodsCount(row, index) {
      console.log(row);
      row.goodsCount = row.boxUnitCount * row.boxNum + row.mainUnitCount * row.mainNum
      this.computedMoney(row)
    },
    couputedGoodsUnitCount(row) {
      //判断是否满足最小销售单位和退货单位
      if (this.params.type == 'SALE' && row.minSaleUnitCount > 0) {
        if (row.goodsCount % row.mainNum != 0) {
          //不满足
          this.$message.error("请输入最小销售单位" + row.minSaleUnitCount + "整数倍的数量")
          return false
        }
      }
      if (this.params.type == 'SALE_RETURN' && row.minReturnUnitCount > 0) {
        if (row.goodsCount % row.mainNum != 0) {
          //不满足
          this.$message.error("请输入最小退货单位" + row.minReturnUnitCount + "整数倍的数量")
          return false
        }
      }

      if (row.boxUnitCount > 0) {
        row.boxNum = Math.floor(row.goodsCount / row.boxUnitCount)
      }
      if (row.mainUnitCount > 0) {
        row.mainNum = Math.floor((row.goodsCount - row.boxUnitCount * row.boxNum) / row.mainUnitCount)
      }
      this.computedMoney(row)
    },
    computedMoney(row){
      //计算价格
      row.noTaxAmount = this.formatNum(row.noTaxBoxPrice * row.boxNum + row.noTaxPrice * row.mainNum)
      row.taxAmount = this.formatNum(row.taxBoxPrice * row.boxNum + row.taxPrice * row.mainNum)
      this.$forceUpdate()
    },
    formatNum: function (num, n = 6) {
      n = n ? parseInt(n) : 0;
      if (n <= 0) {
        return Math.round(num);
      }
      num = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); //四舍五入
      num = Number(num).toFixed(n); //补足位数
      return num;
    },
    changeLeftSelect(sel) {
      this.leftGoodsSelect = sel
    },
    changeResultGoodsSelect(sel) {
      this.resultGoodsSelect = sel
    },
    handleCheckChange() {
      console.log(123)
      // 传递给 data 属性的数组中该节点所对应的对象、节点本身是否被选中、节点的子树中是否有被选中的节点
      //rows为选中的数据
      let rows = this.$refs.typeTree.getCheckedNodes()
      if (rows.length == 0) {
        return false;
      }
      this.selectTypes = rows.map(r => r.id)
      this.getGoodsList()
    },
    getTypeList() {
      let obj = {page: 0, size: 999}
      if (this.searchType) {
        obj = Object.assign(obj, {keyword: this.searchType})
      }
      getTypeList(obj).then(res => {
        this.typeList = res
      })
    },
    getGoodsList() {
      let obj = Object.assign(this.params, {page: 1, size: 50})
      if (this.searchGoods) {
        obj = Object.assign(obj, {keyword: this.searchGoods})
      }


      obj = Object.assign(obj, {goodsTypeIds: this.selectTypes.toString()})

      let arr = this.goodsList.map(good => {
        return good.goodsId
      })
      getGoods(obj).then(res => {
        for (let obj of res.content) {
          if (arr.indexOf(obj.goodsId) < 0) {
            //给这个goods 添加自定义属性
            obj['boxNum'] = 0
            obj['mainNum'] = 0
            obj['goodsCount'] = 0

            this.goodsList.push(obj)
          }
        }

        // this.goodsList = this.goodsList.concat(res.content)
      })

    },
    closedDialog() {
      this.$emit("update:showAddBatchDialog", false)
    },
    addLeft() {
      //只在右边删除
      let resultIds = this.resultGoods.map(result => result.id)
      this.resultGoodsSelect.forEach(result => {
        let _in = resultIds.indexOf(result.id)
        if (_in > -1) {
          this.resultGoods.splice(_in, 1)
        }
      })

    },
    addRight() {
      //添加到右边，防止重复添加
      let resultIds = this.resultGoods.map(result => result.goodsId)
      console.log(this.leftGoodsSelect);
      this.leftGoodsSelect.forEach(left => {
        if (resultIds.indexOf(left.goodsId) < 0) {
          this.resultGoods.push(left)
        }
      })
      this.$forceUpdate()
    },
    submitCU() {
      //判断一下每个商品的数量是不是最小的数量的倍数
      for(let obj of this.resultGoods){
        if(!this.checkMinUnitCount(obj)){
          return false;
        }
      }


      this.closedDialog()
      this.$emit("change", this.resultGoods)
    },
    //判断是否满足最小单位
    checkMinUnitCount(row){
      if (this.type == 'SALE' && row.minSaleUnitCount > 0) {
        if (row.goodsCount % row.mainNum != 0) {
          //不满足
          this.$message.error("请修改商品【"+row.goodsName+"】的数量为最小销售单位【" + row.minSaleUnitCount + "】整数倍")
          return false
        }
      }
      if (this.type == 'SALE_RETURN' && row.minReturnUnitCount > 0) {
        if (row.goodsCount % row.mainNum != 0) {
          //不满足
          this.$message.error("请修改商品【"+row.goodsName+"】的数量为最小销售单位【" + row.minReturnUnitCount + "】整数倍")
          return false
        }
      }
      return true;
    }
  }
}
</script>

<style scoped>
.cu-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-top: 20px;
}
</style>
